package controllers.tinkerforge;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;

import models.SensorConfig;
import models.SensorData;

import org.apache.log4j.Logger;

import play.db.jpa.JPA;
import play.jobs.Job;
import ch.bfh.abcm.rems.interfaces.tinkerforge.TFSensorDataPersister;
import ch.bfh.abcm.rems.sensors.tinkerforge.TFSensorConfigDefinition;
import ch.bfh.abcm.rems.sensors.tinkerforge.TFSensorType;

public class REMSTFSensorDataPersister implements TFSensorDataPersister {
    
    int i = 0;

    private Logger sensorDataLogger = Logger.getLogger("sensorData");

    @Override
    public void saveSensorData(int value, String sensorUID, String host, TFSensorType type) {
        sensorDataLogger.info("Received Sensordata: Type=" + type + " UID=" + sensorUID + " Value=" + value + " "
                + type.getUnit());
        SensorData data = new SensorData(value, sensorUID, host, type);
        new SaveJob(data).now();
    }

    @Override
    public void sensorConfigurationHasChanged(ArrayList<TFSensorConfigDefinition> definitions) {
        play.Logger.debug("New Config is Available -> delete the Old config from DB");
        deleteAllSensorConfig();
        play.Logger.debug("Insert new Sensorconfig in DB");
        for (TFSensorConfigDefinition definition : definitions) {
            SensorConfig sensorConfig = new SensorConfig(definition.getSensorType(), definition.getUid(),
                    definition.getHost(), definition.getHostUID());
            sensorConfig.save();
        }
    }

    private void deleteAllSensorConfig() {
        List<SensorConfig> oldConfigs = SensorConfig.findAll();
        for (SensorConfig sensorConfig : oldConfigs) {
            play.Logger.warn("Deleting SensorConfig: %s",  sensorConfig);
            sensorConfig.delete();
        }
    }

    private class SaveJob extends Job{
        
        private SensorData data;
        
        private SaveJob(SensorData data){
            this.data = data;
        }

        @Override
        public void doJob() throws Exception {
            data.save();
        }
    }


}
